package com.baiyang.app;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.baiyang.app.databinding.ActivityMainBinding;
import com.baiyang.app.tool.LogUtils;
import com.baiyang.app.ui.login.LoginActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 主界面
 * 技术说明：
 * 1.使用了MVVM设计模式
 * 2.使用Timer实现定时执行任务，并用MVVM实现UI界面的修改  -  子线程不能直接修改UI线程组件，可以修改成员变量
 * 3.使用动态授权
 * 4.采用线程进行本地文件IO操作LogUtils
 * getExternalFilesDir("").getAbsolutePath() 获取绝对路径
 */
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding activityMainBinding;
    private MainViewModel mainViewModel;
    /**
     * TimkerTask 方式实现
     */
    private Timer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        requestPermission();
        LogUtils.getLogUtils().setPath(getExternalFilesDir("").getAbsolutePath());
        initHandle();
    }

    private void initHandle() {
        mainViewModel.getSecond().observe(this,e->{
            if("0".equals(e)){
                timer.cancel();
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
                finish();
            }
            activityMainBinding.countdown.setText(e);
        });
    }

    private void timerTask() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            private int second = 3;
            @Override
            public void run() {
                LogUtils.i("MainActivity",String.valueOf(second));
                mainViewModel.setSecond(String.valueOf(second--));
            }
        };
        timer.schedule(task,0,1000);
    }

    //申请权限返回码
    private final int REQUEST_PERMISSION_CODE = 0x01;
    //可以使用Manifest.permission.***表示
    private final String[] permissions = new String[]{
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.ACCESS_NETWORK_STATE",
            "android.permission.CAMERA"};
    /**
     * 动态申请权限
     */
    private void requestPermission() {
        List<String> requestPermissions = new ArrayList<>();
        for (String permission:permissions) {
            //判断用户是否已经授权
            if (ContextCompat.checkSelfPermission(this,
                    permission) != PackageManager.PERMISSION_GRANTED){
                //如果用户没有授权
                requestPermissions.add(permission);
            }
        }
        /**
         * 用户动态授权
         * 执行该代码后，将进入授权界面，此时主线程继续执行
         * 用户授权结果将被onRequestPermissionsResult方法接受，如果需要处理则重写该方法
         */
        if(requestPermissions.size() != 0){
            String[] strs = requestPermissions.toArray(new String[requestPermissions.size()]);
            ActivityCompat.requestPermissions(this, strs, REQUEST_PERMISSION_CODE);
        }else{
            // 开启读秒进行跳转
            timerTask();
        }
    }

    /**
     * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
     * @param permissions The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //授权结果的处理逻辑
        // 开启读秒进行跳转
        timerTask();
    }
}